package com.wngbms.netty.book._06endec._01;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.embedded.EmbeddedChannel;

import java.nio.charset.StandardCharsets;
import java.util.Random;

public class StringReplayDecoderTest {

    public static void main(String[] args) {
        ChannelInitializer<EmbeddedChannel> channelInitializer = new ChannelInitializer<EmbeddedChannel>() {

            @Override
            protected void initChannel(EmbeddedChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                // 顺序不能反
                pipeline.addLast(new StringReplayDecoder());
                pipeline.addLast(new StringProcessHandler());
            }
        };

        EmbeddedChannel embeddedChannel = new EmbeddedChannel(channelInitializer);

        byte[] bytes = "苹果手机真香".getBytes(StandardCharsets.UTF_8);

        Random random = new Random();
        for (int i = 0; i < 100; i++) {
            int i1 = random.nextInt(4) + 1;

            ByteBuf buffer = Unpooled.buffer();
            buffer.writeInt(i1 * bytes.length);
            embeddedChannel.writeInbound(buffer);

            for (int i2 = 0; i2 < i1; i2++) {
                buffer = Unpooled.buffer();
                buffer.writeBytes(bytes);
                embeddedChannel.writeInbound(buffer);
            }
        }
    }

}
